package com.drojian.side;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.drojian.demo.R;
import com.drojian.demo3.dataStorage.SQLite.MyDatabaseHelper;
import com.drojian.demo3.multimedia.ImageUtil;
import com.drojian.root.database.SqlUser;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class InformationActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageView image;
    private EditText userName,passWord,describe,sex,age,hobby,height,weight;
    private Button submit,cancel,btn1,btn2;
    private Cursor user;
    private Uri photoURI;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.side_activity_information);
        initView();
        initData();
    }

    private void initView() {
            image = findViewById(R.id.image);
            userName = findViewById(R.id.userName);
            passWord = findViewById(R.id.passWord);
            btn1 = findViewById(R.id.btn1);
            btn2 = findViewById(R.id.btn2);
            describe = findViewById(R.id.describe);
            sex = findViewById(R.id.sex);
            age = findViewById(R.id.age);
            hobby = findViewById(R.id.hobby);
            height = findViewById(R.id.height);
            weight = findViewById(R.id.weight);
            submit = findViewById(R.id.submit);
            cancel = findViewById(R.id.cancel);
            submit.setOnClickListener(this);
            cancel.setOnClickListener(this);
            btn1.setOnClickListener(this);
            btn2.setOnClickListener(this);
    }

    private void initData() {
        SqlUser user1 = new SqlUser(this, "user.db", null, 1);
        SQLiteDatabase db = user1.getWritableDatabase();
        String username1 = getIntent().getStringExtra("username");
        user = db.query("user", null, "username = ?", new String[]{username1}, null, null, null);
        if (user != null && user.moveToFirst()) {
            do {
                int imageIndex = user.getColumnIndex("image");
                int usernameIndex = user.getColumnIndex("username");
                int passwordIndex = user.getColumnIndex("password");
                int descriptionIndex = user.getColumnIndex("description");
                int sexIndex = user.getColumnIndex("sex");
                int ageIndex = user.getColumnIndex("age");
                int hobbyIndex = user.getColumnIndex("hobby");
                int heightIndex = user.getColumnIndex("height");
                int weightIndex = user.getColumnIndex("weight");

                byte[] imageBytes = user.getBlob(imageIndex);
                Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
                String username6 = user.getString(usernameIndex);
                String password6 = user.getString(passwordIndex);
                String description6 = user.getString(descriptionIndex);
                String sex6 = user.getString(sexIndex);
                int age6 = user.getInt(ageIndex);
                String hobby6 = user.getString(hobbyIndex);
                double height6 = user.getDouble(heightIndex);
                double weight6 = user.getDouble(weightIndex);

                image.setImageBitmap(bitmap);
                image.setImageBitmap(bitmap);
                userName.setText(username6);
                passWord.setText(password6);
                describe.setText(description6);
                sex.setText(sex6);
                age.setText(String.valueOf(age6));
                hobby.setText(hobby6);
                height.setText(String.valueOf(height6));
                weight.setText(String.valueOf(weight6));
            } while (user.moveToNext());

        }else{
            Toast.makeText(this,"有错误",Toast.LENGTH_SHORT).show();
        }

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.submit:
                updateData();
                break;
            case R.id.cancel:
                finish();
                break;
            case R.id.btn1:
                takePhoto();
                break;
            case R.id.btn2:
                choosePhoto();
                break;
        }
    }
    private void updateData() {
        if (user != null && user.moveToFirst()) {
            SqlUser aa = new SqlUser(this, "user.db", null, 1);
            SQLiteDatabase db = aa.getWritableDatabase();
            int idIndex = user.getColumnIndex("id");
            int id = user.getInt(idIndex);
            Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 可以选择JPEG或PNG等格式，这里选择了PNG且质量为100（无损压缩）
            bitmap.compress(Bitmap.CompressFormat.PNG, 10, baos);
            byte[] imageBytes = baos.toByteArray();
            Editable setUserName = userName.getText();
            Editable setPassWord = passWord.getText();
            Editable setDescribe = describe.getText();
            Editable setSex = sex.getText();
            Editable setAge = age.getText();
            Editable setHobby = hobby.getText();
            Editable setHeight = height.getText();
            Editable setWeight = weight.getText();

            ContentValues values = new ContentValues();
            values.put("image", imageBytes);
            values.put("username", setUserName.toString());
            values.put("password", setPassWord.toString());
            values.put("description", setDescribe.toString());
            values.put("sex", setSex.toString());
            values.put("age", String.valueOf(setAge));
            values.put("hobby", setHobby.toString());
            values.put("height", String.valueOf(setHeight));
            values.put("weight", String.valueOf(setWeight));
            db.update("user", values, "id = ?", new String[]{String.valueOf(id)});
            Toast.makeText(this,"修改成功，请重新登陆",Toast.LENGTH_SHORT).show();

            finish();
        }
    }
    //2.权限判定
    private void takePhoto() {
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED){
            // 有权限去拍照
            doTake();
        }else{
            //申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},1);
        }
    }
    //3.接受权限申请结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 1){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                doTake();
            }else {
                Toast.makeText(this,"你没有获得摄像头权限",Toast.LENGTH_SHORT).show();
            }
        }else if(requestCode == 0){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                openAlbum();
            }else {
                Toast.makeText(this,"你没有获得相册权限",Toast.LENGTH_SHORT).show();
            }
        }
    }
    //4.执行拍照
    private void doTake() {
        File imageTemp = new File(getExternalCacheDir(),"imageOut.jpeg");
        if(imageTemp.exists()){
            imageTemp.delete();
        }
        try {
            imageTemp.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(Build.VERSION.SDK_INT > 24){
            photoURI = FileProvider.getUriForFile(this, "com.drojian.demo.fileprovider", imageTemp);
        }else {
            photoURI = Uri.fromFile(imageTemp);
        }
        Intent intent = new Intent();
        intent.setAction("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
        startActivityForResult(intent,1);
    }
    //5.设置照片
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1){
            if(resultCode == RESULT_OK){
                try {
                    //处理照片
                    InputStream inputStream = getContentResolver().openInputStream(photoURI);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    image.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
        }else if(requestCode == 0){
            if(Build.VERSION.SDK_INT < 19){
                Uri uri = data.getData();
                String imagePath = getImagePath(uri,null);
                displayImage(imagePath);
            }else{
                handleImageOnApi19(data);
            }
        }
    }
    @TargetApi(19)
    private void handleImageOnApi19(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if(DocumentsContract.isDocumentUri(this,uri)){
            String documentId = DocumentsContract.getDocumentId(uri);
            if(TextUtils.equals(uri.getAuthority(),"com.android.providers.media.documents")){
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if (TextUtils.equals(uri.getAuthority(),"com.android.providers.downloads.documents")){
                if(documentId != null && documentId.startsWith("msf:")){
                    resolveMSFContent(uri,documentId);
                    return;
                }
                Uri conteneUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                imagePath = getImagePath(conteneUri,null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            imagePath = getImagePath(uri, null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }
    private void resolveMSFContent(Uri uri, String documentId) {
        File file = new File(getCacheDir(), "temp_file" + getContentResolver().getType(uri).split("/")[1]);
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
            OutputStream outputStream = new FileOutputStream(file);
            byte[] buffer = new byte[4 * 1024];
            int read;
            while((read = inputStream.read(buffer)) != -1){
                outputStream.write(buffer,0,read);
            }
            outputStream.flush();

            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
            image.setImageBitmap(bitmap);
            String s = ImageUtil.imageToBase64(bitmap);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private String getImagePath(Uri uri,String selection){
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null, null);
        if(cursor != null){
            if(cursor.moveToFirst()){
                path =  cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }
    private void displayImage(String imagePath){
        if(imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            image.setImageBitmap(bitmap);
        }
    }


    //2.权限判定
    private void choosePhoto() {
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED){
            // 打开相册
            openAlbum();
        }else{
            //申请权限
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},0);
        }

    }
    //3.接受权限申请结果上边的onRequestPermissionsResult
    //4.执行打开相册
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,0);
    }
    //5.接收上边的onActivityResult
}